const http = require('http')
const URL = require('url')
const PATH = require('path')
const Koa = require('koa')
const KoaViews = require('koa-views')
const koaBodyParser = require('koa-better-body')
const favicon = require('./middleware/favicon')
const log = require('./middleware/log')
const loader = require('./middleware/loader')
const error = require('./middleware/error')
const expand = require('./middleware/expand')
const registerRouters = require('./middleware/restRouter')
const { viewsRoot, httpPort, debug } = require('./configure')


module.exports = class Server  {
    constructor () {
        this.app = new Koa();
        this.service = http.createServer(this.app.callback());
        this.middleware(this.app)
        this.registerRouters(this.app)
    }

    // 挂载中间件
    middleware (app) {
        app.use(log({
            ignore: /\.(js|woff)$/
        }));
        app.use(favicon);
        app.use(expand);
        app.use(error);

        app.use(KoaViews(viewsRoot, {
            extension: 'pug'
        }));

        app.use(koaBodyParser({
            formLimit: "5000000",
            textLimit: "5000000",
            jsonLimit: "5000000",
            maxFieldsSize: "5000000"
        }));

        loader({
          env: debug,
          app: app
        })

    }

    // 注册路由
    registerRouters (app) {
        app.use(registerRouters(`${__dirname}/controller`));
        app.use(async (ctx, next) => {
          if (!ctx.body) {
            await ctx.render('index', {
                production: process.env.NODE_ENV
            })
          }
        })
    }

    // run
    start(port = httpPort, cb) {
        this.service.listen(port, () => {
            console.log('listen on ' + port)
            cb && cb()
        });
    }

}
